package com.lvmama.controller.rhino.topic;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.lvmama.common.enums.CommonParentType;
import com.lvmama.common.result.CodeMessage;
import com.lvmama.common.result.Result;
import com.lvmama.common.utils.DateUtil;
import com.lvmama.pojo.dto.rhino.topic.SpecialTopicDTO;
import com.lvmama.pojo.entity.rhino.topic.*;
import com.lvmama.service.rhino.topic.PositionAnalysisService;
import com.lvmama.service.rhino.topic.StatisticCodeService;
import com.lvmama.utils.ToolUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("/specialTopic")
@Slf4j
public class SpecialTopicController {

    @Autowired
    private PositionAnalysisService positionAnalysisService;
    @Autowired
    private StatisticCodeService statisticCodeService;


    /**
     * @param @param  choose_date
     * @param @param  themeName
     * @param @param  page_currentNum
     * @param @param  page_size
     * @param @return 设定文件
     * @return Map<String,Object> 返回类型
     * @throws
     * @Title: getThemeTab
     * @Description: 分页ajax请求专题列表
     */
    @PostMapping("/topicAjaxData")
    @ResponseBody
    public Result<Map<String, Object>> getThemeTab(@RequestBody SpecialTopicDTO specialTopicDTO) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        // 查询日期条件处理
        Map<String, Date> dateMap = ToolUtils.getQueryDate(specialTopicDTO.getChooseTime());
        Date beginDate = dateMap.get("beginDate");
        Date endDate = dateMap.get("endDate");

        // 封装请求参数
        PositionAnalysis positionAnalysisVo = new PositionAnalysis();
        positionAnalysisVo.setStartDate(beginDate);
        positionAnalysisVo.setEndDate(endDate);
        positionAnalysisVo.setName(specialTopicDTO.getThemeName());
        getPaltfrom(specialTopicDTO.getPlatform(),positionAnalysisVo);
        positionAnalysisVo.setPage_size(specialTopicDTO.getPageSize());
        positionAnalysisVo.setCurrentPage(specialTopicDTO.getPageCurrentNum());
        PageInfo<PositionAnalysis> page = positionAnalysisService.getTopicList(positionAnalysisVo);
        List<PositionAnalysis> pas = page.getList();
        List<PitPV> pitPVS = positionAnalysisService.getAllPitPV(positionAnalysisVo);

        for(PositionAnalysis pa:pas){
            for(PitPV pv:pitPVS){
                if(pv.getCode().equals(pa.getCode())){
                    pa.setOrderAmount(pv.getOrderAmount());
                    pa.setOrderMoney(pv.getOrderMoney());
                    pa.setPayAmount(pv.getPayAmount());
                    pa.setPayMoney(pv.getPayMoney());
                    break;
                }
            }
        }
        for(PositionAnalysis pa:pas){
            if(pa.getOrderMoney()==null){
                pa.setOrderMoney(0d);
            }
            if(pa.getPayMoney()==null){
                pa.setPayMoney(0d);
            }
        }

        Collections.sort(pas,new Comparator<PositionAnalysis>() {
            @Override
            public int compare(PositionAnalysis o1, PositionAnalysis o2) {
                // 返回值为int类型，大于0表示正序，小于0表示逆序
                return o2.getClickNum()-o1.getClickNum();
            }
        });

        page = new PageInfo<>(pas);
        resultMap.put("page", page);
        return Result.success(resultMap);
    }

    /**
     * 获取主题点击量 曝光量
     *
     * @return
     */
    @PostMapping("/topicClickData")
    @ResponseBody
    public Result<Map<String, Object>> getTopicClickData(@RequestBody SpecialTopicDTO specialTopicDTO) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        // 查询日期条件处理
        Map<String, Date> dateMap = ToolUtils.getQueryDate(specialTopicDTO.getChooseTime());
        Date beginDate = dateMap.get("beginDate");
        Date endDate = dateMap.get("endDate");

        // 封装请求参数
        PositionAnalysis positionAnalysisVo = new PositionAnalysis();
        positionAnalysisVo.setStartDate(beginDate);
        positionAnalysisVo.setEndDate(endDate);
        positionAnalysisVo.setCode(specialTopicDTO.getCode());
        getPaltfrom(specialTopicDTO.getPlatform(),positionAnalysisVo);
        positionAnalysisVo.setPage_size(10);
        positionAnalysisVo.setCurrentPage(1);
        PageInfo<PitPV> page = positionAnalysisService.getTopicPVByCode(positionAnalysisVo);
        page.getList().remove(page.getList().size()-1);
        resultMap.put("topicPVList", page.getList());
        return Result.success(resultMap);
    }


    /**
     * 获取主题点击量 曝光量
     *
     * @return
     */
    @PostMapping("/topicClickAll")
    @ResponseBody
    public Result<Map<String, PageInfo<PitPV>>> getTopicClickAll(@RequestBody SpecialTopicDTO specialTopicDTO) {
        Map<String, PageInfo<PitPV>> result = new HashMap<>();
        // 查询日期条件处理
        Map<String, Date> dateMap = ToolUtils.getQueryDate(specialTopicDTO.getChooseTime());
        Date beginDate = dateMap.get("beginDate");
        Date endDate = dateMap.get("endDate");

        // 封装请求参数
        PositionAnalysis positionAnalysisVo = new PositionAnalysis();
        positionAnalysisVo.setStartDate(beginDate);
        positionAnalysisVo.setEndDate(endDate);
        positionAnalysisVo.setCode(specialTopicDTO.getCode());
        positionAnalysisVo.setPage_size(specialTopicDTO.getOrderCondition().getPageSize());
        positionAnalysisVo.setCurrentPage(specialTopicDTO.getOrderCondition().getCurrentPage());
        positionAnalysisVo.setName("tab_name");
        getPaltfrom(specialTopicDTO.getPlatform(),positionAnalysisVo);
        PageInfo<PitPV> page = positionAnalysisService.getTopicPVByCode(positionAnalysisVo);

        result.put("page", page);
        return Result.success(result);
    }


    /**
     * 图表数据
     *
     * @return
     * @throws Exception
     */
    @PostMapping("/chartData")
    @ResponseBody
    public Result<Map<String, Object>> chartData(@RequestBody SpecialTopicDTO specialTopicDTO){
        Map<String, Object> resultMap = new HashMap<String, Object>();
        PositionAnalysis pit = new PositionAnalysis();
        // 查询日期条件处理
        Map<String, Date> dateMap = ToolUtils.getQueryDate(specialTopicDTO.getChooseTime());
        Date beginDate = dateMap.get("beginDate");
        Date endDate = dateMap.get("endDate");
        pit.setStartDate(beginDate);
        pit.setEndDate(endDate);
        pit.setCode(specialTopicDTO.getCode());
        pit.setName(specialTopicDTO.getThemeName());
        getPaltfrom(specialTopicDTO.getPlatform(),pit);
        List<PositionAnalysis> pitListByCategory = positionAnalysisService.getPitListByCategory(pit);
        List<PositionAnalysis> pitListByDate = positionAnalysisService.getPitListByDate(pit);
        List<PositionAnalysis> pitBarByCategory = positionAnalysisService.getPitBarByCategory(pit);

        // 总订单量 总订单金额
        int payAmountTotal = 0;
        double payMoneyTotal = 0;

        // 饼状图数据
        JSONArray payAmountArr = new JSONArray();
        JSONArray payMoneyArr = new JSONArray();
        for (PositionAnalysis positionAnalysis : pitListByCategory) {
            if (positionAnalysis.getPayMoney() == null) {
                continue;
            }
            payAmountTotal += positionAnalysis.getPayAmount();
            payMoneyTotal += positionAnalysis.getPayMoney();
            JSONObject payAmountOb = new JSONObject();
            payAmountOb.put("categoryName", CommonParentType.getCategoryShowName(positionAnalysis.getCategoryId()));
            payAmountOb.put("amount", positionAnalysis.getPayAmount());
            payAmountArr.add(payAmountOb);
            JSONObject payMoneyOb = new JSONObject();
            payMoneyOb.put("categoryName", CommonParentType.getCategoryShowName(positionAnalysis.getCategoryId()));
            payMoneyOb.put("amount", positionAnalysis.getPayMoney());
            payMoneyArr.add(payMoneyOb);
        }
        // 柱状图数据
        List<String> categoryNames = new ArrayList<>();
        JSONArray arr2 = new JSONArray();
        for (PositionAnalysis positionAnalysis : pitBarByCategory) {
            String categoryName = CommonParentType
                    .getCategoryShowName(positionAnalysis.getCategoryId());
            if (StringUtils.isNotEmpty(categoryName)) {
                categoryNames.add(categoryName);
                JSONObject o = new JSONObject();
                o.put("categoryName", categoryName);
                o.put("amount", positionAnalysis.getCompletedPaymentPageSum()
                        + positionAnalysis.getDetailPageSum()
                        + positionAnalysis.getFillOrderPageSum()
                        + positionAnalysis.getPendingPaymentPageSum());
                arr2.add(o);
            }
        }

        // 折线图数据
        String[] dateAxis = DateUtil.getBetweenTime(beginDate, endDate, "yyyy/MM/dd");
        List<String> dateList = Arrays.asList(dateAxis);
        JSONArray arr = new JSONArray();
        for (String date : dateList) {
            for (String category : categoryNames) {
                Integer amount = 0;
                for (PositionAnalysis position : pitListByDate) {
                    String categoryName = CommonParentType.getCategoryShowName(position.getCategoryId());
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
                    String time = sdf.format(position.getTime());
                    if (category.equals(categoryName) && date.equals(time)) {
                        amount += position.getCompletedPaymentPageSum()
                                + position.getDetailPageSum()
                                + position.getFillOrderPageSum()
                                + position.getPendingPaymentPageSum();
                    }
                }
                JSONObject o = new JSONObject();
                o.put("categoryName", category);
                o.put("time", date);
                o.put("amount", amount);
                arr.add(o);
            }
        }
        resultMap.put("payAmountTotal", payAmountTotal);
        resultMap.put("payMoneyTotal", payMoneyTotal);
        resultMap.put("jsonData", arr);
        resultMap.put("jsonData2", arr2);
        resultMap.put("payAmountJsonData", payAmountArr);
        resultMap.put("payMoneyJsonData", payMoneyArr);
        return Result.success(resultMap);
    }

    /**
     * @param @param  chooseTime
     * @param @param  category_id
     * @param @return
     * @param @throws Exception 设定文件
     * @return Map<String,Object> 返回类型
     * @throws
     * @Title: getPageChartData
     * @Description: 根据品类获取相关页面的引流
     */
    @PostMapping("/getPageChartData")
    @ResponseBody
    public Result<Map<String, Object>> getPageChartData(@RequestBody SpecialTopicDTO specialTopicDTO) {
        Map<String, Object> resultMap = new HashMap<String, Object>();

        PositionAnalysis pit = new PositionAnalysis();
        // 查询日期条件处理
        Map<String, Date> dateMap = ToolUtils.getQueryDate(specialTopicDTO.getChooseTime());
        Date beginDate = dateMap.get("beginDate");
        Date endDate = dateMap.get("endDate");
        pit.setStartDate(beginDate);
        pit.setEndDate(endDate);
        pit.setCode(specialTopicDTO.getCode());
        getPaltfrom(specialTopicDTO.getPlatform(),pit);
        pit.setCategoryId(CommonParentType.getCategoryValueByShowName(specialTopicDTO.getThemeName()));
        PositionAnalysis pitForPage=new PositionAnalysis();
        try {
             pitForPage = positionAnalysisService.getPageNumByCategory(pit);
        } catch (Exception e) {
            log.error("getPageChartData error{}",e);
            return Result.error(CodeMessage.SERVER_ERROR);
        }
        resultMap.put("pitForPage", pitForPage);
        return Result.success(resultMap);
    }

    /**
     * 查询专题漏斗数据
     *
     * @param query
     * @return
     */
    @PostMapping("/getTopicFunnel")
    @ResponseBody
    public Result<List<SpecialTopicFunnelData>> getTopicFunnel(@RequestBody TopicFunnelDataQuery query) {
        List<SpecialTopicFunnelData> funnelDataList = new ArrayList<>();
        try {
            funnelDataList = positionAnalysisService.getTopicFunnel(query);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.success(funnelDataList);
    }


    public void getPaltfrom(String platform,PositionAnalysis positionAnalysisVo){
        if (StringUtils.isNotEmpty(platform)) {
            List<String> statisticCodeList = new ArrayList<String>();
            String[] platforms = StringUtils.split(platform,",");
            for(String pf:platforms){
                statisticCodeList.addAll(statisticCodeService.getDeviceCodeByLikeName(pf));
            }
            positionAnalysisVo.setStatisticCodeList(statisticCodeList);
        }
    }




}
